package com.app.couponsharelife.ui.main.home.local

import android.app.AlertDialog
import android.content.Intent
import android.graphics.Color
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.gson.Gson
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout
import com.lcodecore.tkrefreshlayout.footer.LoadingView
import com.lcodecore.tkrefreshlayout.header.progresslayout.ProgressLayout
import com.app.couponsharelife.R
import com.app.couponsharelife.base.BaseActivity
import com.app.couponsharelife.data.bean.LifeShopPageBean
import com.app.couponsharelife.data.bean.PageTipBean
import com.app.couponsharelife.data.bean.SearchHistoryBean
import com.app.couponsharelife.manage.Contacts
import com.app.couponsharelife.ui.adapter.HistoryRecordListAdapter
import com.app.couponsharelife.ui.adapter.LocalShopsListAdapter
import com.app.couponsharelife.ui.listener.OnClickListener
import com.app.couponsharelife.ui.main.login.NewLoginActivity
import com.app.couponsharelife.ui.viewmodel.LocalViewModel
import com.app.couponsharelife.utils.AppUtils
import com.app.fuquan.data.bean.PageStatus
import kotlinx.android.synthetic.main.activity_local_shops_search.*
import java.util.HashMap

class LocalShopsSearchActivity : BaseActivity() {

    override val viewLayoutId: Int get() = R.layout.activity_local_shops_search

    private var page = 1

    /**
     * 标记下拉刷新还是上拉加载
     */
    private var isRefresh = true

    /**
     * 标记是否在搜索页
     */
    private var isSearchPage = true

    /**
     * 搜索记录
     */
    private var historyList = mutableListOf<String>()

    /**
     * 热门搜索
     */
    private var hotList = mutableListOf<String>()

    /**
     * 搜索关键字
     */
    private var keyWord = ""

    private var mViewModel: LocalViewModel? = null

    override fun initViews() {
        initRefreshLayout()
        initRecyclerView()
        initClickEvent()
    }

    private fun initClickEvent() {
        ivBack.setOnClickListener {
            onBackPressed()
        }
        tvRightBtn.setOnClickListener {
            searchEditTextContent()
        }
        etSearchWord.setOnEditorActionListener { arg0, arg1, arg2 ->
            if (arg1 == EditorInfo.IME_ACTION_SEARCH) {
                searchEditTextContent()
            }
            false
        }
        ivDeleteSearchRecord.setOnClickListener { showDeleteDialog() }
    }

    private fun searchEditTextContent() {
        if (TextUtils.isEmpty(etSearchWord.text)) {
            showToastMsg("搜索内容不能为空")
        } else {
            AppUtils.hideInputBoard(this, etSearchWord)
            keyWord = etSearchWord.text.toString().trim()
            goSearchDetailPage()
        }
    }

    private fun initFlowLayout() {
        mSearchHistory.removeAllViews()
        val inflater = LayoutInflater.from(this)
        for (hot in hotList) {
            val view = inflater.inflate(R.layout.hot_search_item, mSearchHistory, false) as TextView
            view.text = hot
            mSearchHistory.addView(view)
        }
        mSearchHistory.setListener { position, view ->
            keyWord = hotList[position]
            goSearchDetailPage()
        }
        clHotSearch.visibility = View.VISIBLE
    }

    private fun goSearchDetailPage() {
        isSearchPage = false
        mScrollView.visibility = View.GONE
        mRefreshLayout.visibility = View.VISIBLE
        etSearchWord.setText(keyWord)
        etSearchWord.setSelection(keyWord.length)
        if (historyList.contains(keyWord))
            historyList.remove(keyWord)
        historyList.add(0, keyWord)
        if (historyList.isEmpty())
            clSearchHistory.visibility = View.GONE
        else
            clSearchHistory.visibility = View.VISIBLE
        (mRecyclerViewHistorySearch.adapter as HistoryRecordListAdapter).notifyDataSetChanged()
        (mRecyclerView.adapter as LocalShopsListAdapter).setData(arrayListOf(PageTipBean("", 0, 0)), 1)
        page = 1
        loadData()
    }

    private fun initRefreshLayout() {
        mRefreshLayout.setFloatRefresh(true)
        mRefreshLayout.setAutoLoadMore(true)
        mRefreshLayout.setEnableLoadmore(true)
        mRefreshLayout.setEnableOverScroll(false)
        val header = ProgressLayout(this)
        header.setColorSchemeResources(R.color.act_main_bot_nav_select_text_color)
        mRefreshLayout.setHeaderView(header)
        mRefreshLayout.setBottomView(LoadingView(this))
        mRefreshLayout.setOnRefreshListener(object : RefreshListenerAdapter() {
            override fun onLoadMore(refreshLayout: TwinklingRefreshLayout?) {
                isRefresh = false
                loadData()
            }

            override fun onRefresh(refreshLayout: TwinklingRefreshLayout?) {
                isRefresh = true
                page = 1
                loadData()
            }
        })
    }

    private fun initRecyclerView() {
        val string = AppUtils.getString("searchHistoryLocalShop", "")
        if (string == "") {
            clSearchHistory.visibility = View.GONE
        } else {
            historyList.clear()
            historyList.addAll(Gson().fromJson(string, SearchHistoryBean::class.java).list)
        }
        if (historyList.isEmpty())
            clSearchHistory.visibility = View.GONE
        else
            clSearchHistory.visibility = View.VISIBLE
        val layoutManager = object : androidx.recyclerview.widget.LinearLayoutManager(this) {
            override fun canScrollVertically(): Boolean {
                return false
            }
        }
        mRecyclerViewHistorySearch.layoutManager = layoutManager
        mRecyclerViewHistorySearch.adapter = HistoryRecordListAdapter(historyList, object : OnClickListener {
            override fun click(arg1: Int, arg2: Any) {
                keyWord = arg2 as String
                goSearchDetailPage()
            }
        })
        mRecyclerView.layoutManager = LinearLayoutManager(this)
        mRecyclerView.adapter = LocalShopsListAdapter(arrayListOf(), object : OnClickListener {
            override fun click(arg1: Int, arg2: Any) {
                if (AppUtils.checkUserLogin()) {
                    val intent = Intent(this@LocalShopsSearchActivity, LocalShopDetailActivity::class.java)
                    intent.putExtra("shopId", (arg2 as LifeShopPageBean.RecordsBean).id)
                    startActivity(intent)
                } else startActivity(Intent(this@LocalShopsSearchActivity, NewLoginActivity::class.java))//startActivity(Intent(this@LocalShopsSearchActivity, LoginActivity::class.java))
            }
        })
    }

    /**
     * 删除搜索记录确认对话框
     */
    private fun showDeleteDialog() {
        val builder = AlertDialog.Builder(this)
        builder.setTitle("提示")
        builder.setMessage("是否清空搜索记录？")
        builder.setNegativeButton("取消") { dialog, _ -> dialog.dismiss() }
        builder.setPositiveButton("删除") { dialog, _ ->
            historyList.clear()
            clSearchHistory.visibility = View.GONE
            (mRecyclerViewHistorySearch.adapter as HistoryRecordListAdapter).notifyDataSetChanged()
            dialog.dismiss()
        }
        builder.setCancelable(false)
        val dialog = builder.show()
        dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(Color.BLACK)
        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(Color.BLACK)
    }

    override fun onStop() {
        AppUtils.setString("searchHistoryLocalShop", Gson().toJson(SearchHistoryBean(historyList)))
        super.onStop()
    }

    override fun onBackPressed() {
        if (isSearchPage) finish() else {
            mScrollView.visibility = View.VISIBLE
            mRefreshLayout.visibility = View.GONE
            isSearchPage = true
        }
    }

    override fun initViewModel() {
        if (mViewModel == null) mViewModel = ViewModelProviders.of(this).get(LocalViewModel::class.java)
        if (!mViewModel!!.getLifeShopPage()!!.hasObservers()) {
            mViewModel!!.getLifeHotKeyword()!!.observe(this, Observer {
                if (it == null) {
                    dismissProgressDialog()
                    showToastMsg("数据出错啦")
                    return@Observer
                }
                when (it.status) {
                    PageStatus.Loading -> {
                        showProgressDialog("请稍候")
                    }
                    PageStatus.Error -> {
                        dismissProgressDialog()
                        mViewModel!!.freshGetLifeShopPage(hashMapOf(), false)
                        showToastMsg(parseErrorDate(it.error!!.message).tip)
                    }
                    PageStatus.Empty -> {
                        dismissProgressDialog()
                        mViewModel!!.freshGetLifeShopPage(hashMapOf(), false)
                        showToastMsg("暂无数据")
                    }
                    PageStatus.Content -> {
                        dismissProgressDialog()
                        mViewModel!!.freshGetLifeShopPage(hashMapOf(), false)
                        if (it.data!!.code == 200 && it.data.data != null && it.data.data!!.isNotEmpty()) {
                            hotList.clear()
                            hotList.addAll(it.data.data!!)
                            initFlowLayout()
                        } else {
                            println("暂无热搜关键字")
                        }
                    }
                }
            })
            mViewModel!!.getLifeShopPage()!!.observe(this, Observer {
                if (it == null) {
                    handleError(parseErrorDate("数据出错啦"))
                    return@Observer
                }
                when (it.status) {
                    PageStatus.Loading -> {
                    }
                    PageStatus.Error -> {
                        mViewModel!!.freshGetLifeShopPage(hashMapOf(), false)
                        handleError(parseErrorDate(it.error!!.message))
                    }
                    PageStatus.Empty -> {
                        mViewModel!!.freshGetLifeShopPage(hashMapOf(), false)
                        handleError(parseErrorDate("暂无数据"))
                    }
                    PageStatus.Content -> {
                        mViewModel!!.freshGetLifeShopPage(hashMapOf(), false)
                        if (it.data!!.code == 200 && it.data.data != null) {
                            handleContent(it.data.data!!)
                        } else {
                            handleError(parseErrorDate("请求失败"))
                        }
                    }
                }
            })
        }
        getLifeHotKeyword()
    }

    private fun handleContent(data: LifeShopPageBean) {
        if (page == 1 && isRefresh) {
            mRefreshLayout.finishRefreshing()
        } else
            mRefreshLayout.finishLoadmore()
        if (data.records.isNotEmpty()) {
            page++
            (mRecyclerView.adapter as LocalShopsListAdapter).setData(data.records, page)
        } else {
            handleError(PageTipBean(if (page == 1) "暂无相关商家～" else "暂无更多商家", R.drawable.ic_no_shop, 1))
        }
    }

    private fun handleError(pageTipBean: PageTipBean) {
        if (page == 1) {
            if (isRefresh) mRefreshLayout.finishRefreshing() else mRefreshLayout.finishLoadmore()
            if ((mRecyclerView.adapter as LocalShopsListAdapter).list[0] is PageTipBean) {
                ((mRecyclerView.adapter as LocalShopsListAdapter).list[0] as PageTipBean).tip = pageTipBean.tip
                ((mRecyclerView.adapter as LocalShopsListAdapter).list[0] as PageTipBean).status = pageTipBean.status
                ((mRecyclerView.adapter as LocalShopsListAdapter).list[0] as PageTipBean).src = pageTipBean.src
                (mRecyclerView.adapter as LocalShopsListAdapter).notifyItemChanged(0)
            }
        } else {
            mRefreshLayout.finishLoadmore()
            showToastMsg(pageTipBean.tip)
        }
    }

    private fun getLifeHotKeyword() {
        val map = HashMap<String, String>()
        map["num"] = "10"
        mViewModel?.freshGetLifeHotKeyword(map, true)
    }

    private fun loadData() {
//        (mRecyclerView.adapter as LocalShopsListAdapter).setData(arrayListOf(PageTipBean("", 0, 0)), 2)

        val map = HashMap<String, String>()
        map["keyword"] = keyWord
        map["Longitude"] = AppUtils.getString("Longitude", Contacts.HZ_CENTER_LONGITUDE)
        map["Latitude"] = AppUtils.getString("Latitude", Contacts.HZ_CENTER_LATITUDE)
        map["distance"] = "10000"
        map["pageNo"] = page.toString()
        mViewModel?.freshGetLifeShopPage(map, true)
    }
}
